import mongoose, { Document, Schema } from 'mongoose'

export interface IRoom extends Document {
  title: string
  description: string
  cover: string
  owner: Schema.Types.ObjectId
  category: string
  tags: string[]
  status: 'preparing' | 'live' | 'ended'
  streamKey: string
  viewers: number
  likes: number
  startTime?: Date
  endTime?: Date
  notice?: string
  settings: {
    chatEnabled: boolean
    danmakuEnabled: boolean
    giftEnabled: boolean
    onlyFollowerChat: boolean
    minFollowTime: number // 粉丝关注时间限制（分钟）
  }
  statistics: {
    totalViewers: number
    maxConcurrent: number
    totalIncome: number
    giftCount: number
  }
  createdAt: Date
  updatedAt: Date
}

const RoomSchema = new Schema(
  {
    title: { type: String, required: true },
    description: { type: String },
    cover: { type: String },
    owner: { type: Schema.Types.ObjectId, ref: 'User', required: true },
    category: { type: String, required: true },
    tags: [{ type: String }],
    status: {
      type: String,
      enum: ['preparing', 'live', 'ended'],
      default: 'preparing',
    },
    streamKey: { type: String, unique: true },
    viewers: { type: Number, default: 0 },
    likes: { type: Number, default: 0 },
    startTime: Date,
    endTime: Date,
    notice: String,
    settings: {
      chatEnabled: { type: Boolean, default: true },
      danmakuEnabled: { type: Boolean, default: true },
      giftEnabled: { type: Boolean, default: true },
      onlyFollowerChat: { type: Boolean, default: false },
      minFollowTime: { type: Number, default: 0 },
    },
    statistics: {
      totalViewers: { type: Number, default: 0 },
      maxConcurrent: { type: Number, default: 0 },
      totalIncome: { type: Number, default: 0 },
      giftCount: { type: Number, default: 0 },
    },
  },
  {
    timestamps: true,
  }
)

// 索引优化
RoomSchema.index({ owner: 1, status: 1 })
RoomSchema.index({ category: 1, status: 1 })
RoomSchema.index({ 'statistics.totalIncome': -1 })
RoomSchema.index({ createdAt: -1 })

export const Room = mongoose.model<IRoom>('Room', RoomSchema)
